import datetime
import os
import re
import time
from weibo_update_min import format_to_mysql
import logzero
import requests,json
from logzero import logger
from utils import get_mongo_collection,re_html_tag

uidRe = re.compile(r"https://weibo.com/(\d+)/.+")
midRe = re.compile(r'act=(\d+)')
current_module = os.path.splitext(os.path.basename(__file__))[0]
logzero.logfile(f"/tmp/{current_module}.log", maxBytes=30_000_000, backupCount=3, encoding='utf-8')

COLLECTION_NAME = current_module
db = get_mongo_collection(COLLECTION_NAME)


# error_db = get_mongo_collection(REPORT_ERROR_COLLECTION_NAME)


def get_weibo_uid(url):
    url = url.split('#')[0] + ':formatted'
    HEADERS = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/61.0.3163.91 Safari/537.36',
        'Referer': url,
        'Cookie':'SINAGLOBAL=5173557185380.206.1511929624287; YF-Page-G0=d0adfff33b42523753dc3806dc660aa7; YF-Ugrow-G0=ad06784f6deda07eea88e095402e4243; _s_tentry=login.sina.com.cn; UOR=ued.lanrentuku.com,widget.weibo.com,login.sina.com.cn; Apache=4235423452747.704.1513909497723; ULV=1513909497789:9:7:4:4235423452747.704.1513909497723:1513825735403; YF-V5-G0=32427df11f152291036145f8d346cc49; login_sid_t=77bf02b597bd9c7453f8a31d9f18b04a; cross_origin_proto=SSL; wb_cusLike_undefined=N; WBtopGlobal_register_version=49306022eb5a5f0b; SCF=AsM2LWUqb9D-MS1UyXTE2J-lHFEgdM4P1kZGUJNkCsBaD_tSZeMV5hTMH2PAI3KSPUpDCIIr12we3XdYNktcQfc.; SUHB=0U1Zrni6YDBlf6; wb_cusLike_5953913429=N; SUB=_2AkMtYPP6dcNxrAZYnfsczWjmboRH-jyetZoMAn7uJhMyAxh87nIUqSVutBF-XCQPBvz2MYFD4_0qOl_GOXLrQgXJ; SUBP=0033WrSXqPxfM72wWs9jqgMF55529P9D9WFPGZhFYQH90cAlulxvDJ2r; WBStorage=c1cc464166ad44dc|undefined'
    }

    info = requests.get(url, headers=HEADERS).text
    uid_arr = uidRe.search(url)

    arr = midRe.search(info)
    try:
        return {'uid': uid_arr.group(1), 'mid': arr.group(1)}
    except IndexError:
        logger.error('正则匹配错误')
        return False , url
    except AttributeError :
        logger.error('正则匹配错误')

        return False,url

def get_page_info(values, adminName):
    uid = values['uid']
    mid = values['mid']
    stop = True
    page = 1
    while stop:
        url = f'https://m.weibo.cn/api/container/getIndex?type=uid&value={uid}&containerid=107603{uid}&page={page}'
        # print(url)
        pageList = requests.get(url).text
        pageList = json.loads(pageList)
        try:
            if pageList.get('msg') and pageList['msg'] != '服务器走丢了':
                logger.error('服务器走丢了')
                time.sleep(3)

                stop=False
                return False
            for i in pageList['data']['cards']:
                if i['card_type'] == 9:
                    if i['mblog']['id'] == str(mid):
                        i['adminName'] = adminName
                        i['cos']='资讯'
                        i['type_'] = '微博博主'
                        i['from_ltyy'] = 1
                        i['update_time'] = datetime.datetime.now()
                        return i
        except:
            logger.error('有报错')
            stop = False
            return False
        page += 1

        if pageList['ok'] == 0 :
            stop = False
            return False

def main(url,adminname,theme_id,tag):
    try:
        data_list = get_weibo_uid(url)
        if data_list:
            weibo_one = get_page_info(data_list, adminname)
            #返回mysql数据结果
            #插入t ag
            if not weibo_one:
                return False, False

            format_mysql=format_to_mysql(weibo_one,theme_id)
            format_mysql['type']=tag
            if format_mysql['contents']['media_type']==2:
                if format_mysql['ext']['video']['pic'].get('url',0):
                    format_mysql['ext']['video']['pic']=format_mysql['ext']['video']['pic']['url']
                if format_mysql['ext']['video']['big_pic'].get('url',0):
                    format_mysql['ext']['video']['big_pic']=format_mysql['ext']['video']['big_pic'].get('url', 0)
            format_mysql['contents']['mongo_id'] = format_mysql['contents']['mongo_id'].replace('py_','')
            return True, format_mysql
    except TypeError as e:
        return False,False
if __name__ == '__main__':
    a1 = time.time()
    a,b=main('https://weibo.com/6224836870/G40LVvG2k?from=page_1005056224836870_profile&wvr=6&mod=weibotime','admin',1,[1])
    print(b)
    print(time.time() - a1)